package com.niiwoo.civet.mobile.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.niiwoo.civet.mobile.vo.request.databackflow.AddressListBackFlowRequestVO;
import com.niiwoo.civet.mobile.vo.request.databackflow.ApplicationListRequestVO;
import com.niiwoo.civet.mobile.vo.request.databackflow.MessageInfoRequestVO;
import com.niiwoo.civet.mobile.vo.request.databackflow.TalkRecordRequestVO;
import com.niiwoo.civet.mobile.vo.request.user.df.StartAfterLoginRequestVO;
import com.niiwoo.civet.trade.dto.request.databackflow.AddressListBackFlowRequestDTO;
import com.niiwoo.civet.trade.service.databackflow.TianChengDataBackFlowDubboService;
import com.niiwoo.civet.user.dto.request.ApplicationListRequestDTO;
import com.niiwoo.civet.user.dto.request.MessageInfoRequestDTO;
import com.niiwoo.civet.user.dto.request.TalkRecordRequestDTO;
import com.niiwoo.civet.user.dto.request.df.StartAfterLoginRequestDTO;
import com.niiwoo.civet.user.service.dataflow.UserDataBackFlowDubboService;
import com.niiwoo.tripod.web.annotation.AuthIgnore;
import com.niiwoo.tripod.web.shiro.UserAuthPrincipal;
import com.niiwoo.tripod.web.util.PrincipalContext;
import com.niiwoo.tripod.web.util.RequestUtil;
import com.niiwoo.tripod.web.vo.Empty;
import com.niiwoo.tripod.web.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * 天称数据回流
 * @author xueyuke
 * @date 2017-12-01
 */
@Slf4j
@RestController
@RequestMapping("/tiancheng/databackflow")
@Api(tags = "天称数据回流", description = "/tiancheng/databackflow")
public class TianChengDataBackFlowController {
    private static final Logger logger= LoggerFactory.getLogger(TianChengDataBackFlowController.class);

    @Reference(version = "1.0.0")
    private UserDataBackFlowDubboService userDataBackFlowDubboService;

    @Reference(version = "1.0.0")
    private TianChengDataBackFlowDubboService tianChengDataBackFlowDubboService;


    @ApiOperation("登录后启动数据回流")
    @PostMapping("/startAfterLogin")
    public Result startAfterLoginBackFlow(HttpServletRequest httpServletRequest, @RequestBody @Valid StartAfterLoginRequestVO startAfterLoginRequestVO){
        String userRealIP = RequestUtil.getUserRealIP(httpServletRequest);
        startAfterLoginRequestVO.setIpAddress(userRealIP);
        UserAuthPrincipal principal = (UserAuthPrincipal) SecurityUtils.getSubject().getPrincipal();
        String userId = principal.getUserId();
        startAfterLoginRequestVO.setUserId(userId);

        String token = SecurityUtils.getSubject().getSession().getId().toString();
        startAfterLoginRequestVO.setSessionId(token);
        log.info("登录后启动数据回流:{}", JSON.toJSONString(startAfterLoginRequestVO));

        StartAfterLoginRequestDTO startAfterLoginRequestDTO = new StartAfterLoginRequestDTO();
        BeanUtils.copyProperties(startAfterLoginRequestVO, startAfterLoginRequestDTO);
        userDataBackFlowDubboService.startAfterLoginBackFlow(startAfterLoginRequestDTO);
        return Result.with(Empty.getInstance());
    }

    @PostMapping("/addressList")
    @ApiOperation("通讯录回流")
    public Empty addressListBackFlow(@RequestBody @Valid AddressListBackFlowRequestVO request) {
        String userId = PrincipalContext.getUserId();
        try {
            request.setUserId(userId);
            logger.info("通讯录前端回流,用户ID={},请求参数={}", userId, request);
            AddressListBackFlowRequestDTO addressListBackFlowRequestDTO = transAddressListBackFlowVO2DTO(request);
            logger.info("通讯录前端回流,用户ID={},转换后请求参数={}", userId, JSON.toJSONString(addressListBackFlowRequestDTO));

            tianChengDataBackFlowDubboService.addressList(addressListBackFlowRequestDTO);
        }catch(Exception e){
            logger.error("通讯录前端回流,用户ID={},发生系统异常,原因={}", userId, e);
        }
        return Empty.getInstance();
    }

//    @PostMapping("/abortiveProject")
//    @ApiOperation("流标事件回流")
//    public Empty abortiveProjectBackFlow(@RequestBody @Valid AbortiveProjectBackFlowRequestVO request) {
//        AbortiveProjectBackFlowRequestDTO abortiveProjectBackFlowRequestDTO=new AbortiveProjectBackFlowRequestDTO();
//        abortiveProjectBackFlowRequestDTO.setDetail(request.getDetail());
//        abortiveProjectBackFlowRequestDTO.setBid(request.getBid());
//        abortiveProjectBackFlowRequestDTO.setCause(request.getCause());
//
//        tianChengDataBackFlowDubboService.abortiveProject(abortiveProjectBackFlowRequestDTO);
//        return Empty.getInstance();
//    }
//
//    @PostMapping("/projectStatusChange")
//    @ApiOperation("标的状态变更事件回流")
//    public Empty projectStatusChangeBackFlow(@RequestBody @Valid ProjectStatusChangeBackFlowRequestVO request) {
//        ProjectStatusChangeBackFlowRequestDTO projectStatusChangeBackFlowRequestDTO=new ProjectStatusChangeBackFlowRequestDTO();
//        projectStatusChangeBackFlowRequestDTO.setFromStatus(request.getFromStatus());
//        projectStatusChangeBackFlowRequestDTO.setProjectId(Long.valueOf(request.getProjectId()));
//        projectStatusChangeBackFlowRequestDTO.setStatus(request.getStatus());
//
//        tianChengDataBackFlowDubboService.projecctStatusChange(projectStatusChangeBackFlowRequestDTO);
//        return Empty.getInstance();
//    }

    private AddressListBackFlowRequestDTO transAddressListBackFlowVO2DTO(AddressListBackFlowRequestVO addressListBackFlowRequestVO){
        AddressListBackFlowRequestDTO addressListBackFlowRequestDTO =new AddressListBackFlowRequestDTO();
        addressListBackFlowRequestDTO.setUserId(addressListBackFlowRequestVO.getUserId());
        addressListBackFlowRequestDTO.setDeviceId(addressListBackFlowRequestVO.getDeviceId());
        addressListBackFlowRequestDTO.setOs(addressListBackFlowRequestVO.getOs());
        addressListBackFlowRequestDTO.setEquipmentStatus(addressListBackFlowRequestVO.getEquipmentStatus());

        List<AddressListBackFlowRequestDTO.Address> address4DTOList=new ArrayList<AddressListBackFlowRequestDTO.Address>();
        for(AddressListBackFlowRequestVO.Address address:addressListBackFlowRequestVO.getAddressList()){
            AddressListBackFlowRequestDTO.Address address4DTO=new AddressListBackFlowRequestDTO.Address();
            address4DTO.setMobile(address.getMobile());
            address4DTO.setRemark(address.getRemark());

            address4DTOList.add(address4DTO);
        }
        addressListBackFlowRequestDTO.setAddressList(address4DTOList);

        return addressListBackFlowRequestDTO;
    }


    @AuthIgnore
    @PostMapping("/messageInfo")
    @ApiModelProperty("短信息数据回流-鲁静")
    @ApiOperation("短信息数据回流-鲁静（登录成功后、授信前、借款前上传授权信息）")
    public Empty messageInfo(@RequestBody @Valid MessageInfoRequestVO requestVO){
        logger.info("短信息数据回流messageInfo{}", JSONObject.toJSONString(requestVO));
        String userId = PrincipalContext.getUserId();
        logger.info("短信息数据回流userId = {}", userId);
        MessageInfoRequestDTO messageInfoRequest = new MessageInfoRequestDTO();
        messageInfoRequest.setDeviceId(requestVO.getDeviceId());
        messageInfoRequest.setUserId(userId);
        List<MessageInfoRequestVO.MessageInfo> messageInfoList = requestVO.getMessageList();
        List<MessageInfoRequestDTO.MessageInfo> messageInfos = new ArrayList<>();
        if(!messageInfoList.isEmpty()){
            messageInfoList.forEach(p -> {
                MessageInfoRequestDTO.MessageInfo messageInfo = new MessageInfoRequestDTO.MessageInfo();
                messageInfo.setTime(p.getTime());
                messageInfo.setSendOrReceive(p.getSendOrReceive());
                messageInfo.setMobile(p.getMobile());
                messageInfo.setContent(p.getContent());
                messageInfos.add(messageInfo);
            });
        }
        messageInfoRequest.setMessageList(messageInfos);
        userDataBackFlowDubboService.messageInfo(messageInfoRequest);
        return Empty.getInstance();
    }


    @AuthIgnore
    @PostMapping("/talkRecord")
    @ApiModelProperty("通话记录数据回流-鲁静")
    @ApiOperation("通话记录数据回流-鲁静（登录成功后、授信前、借款前上传授权信息）")
    public Empty talkRecord(@RequestBody @Valid TalkRecordRequestVO talkRecordRequestVO){
        logger.info("通话记录数据回流talkRecord{}", JSONObject.toJSONString(talkRecordRequestVO));
        String userId = PrincipalContext.getUserId();
        logger.info("通话记录数据回流userId = {}", userId);
        TalkRecordRequestDTO talkRecordRequestDTO = new TalkRecordRequestDTO();
        talkRecordRequestDTO.setDeviceId(talkRecordRequestVO.getDeviceId());
        talkRecordRequestDTO.setUserId(userId);
        List<TalkRecordRequestVO.TalkRecord> talkRecordList = talkRecordRequestVO.getCallRecordsList();
        List<TalkRecordRequestDTO.TalkRecord> messageInfos = new ArrayList<>();
        if(!talkRecordList.isEmpty()){
            talkRecordList.forEach(p -> {
                TalkRecordRequestDTO.TalkRecord talkRecord = new TalkRecordRequestDTO.TalkRecord();
                talkRecord.setDuration(p.getDuration());
                talkRecord.setMobile(p.getMobile());
                talkRecord.setSendOrReceive(p.getSendOrReceive());
                talkRecord.setTime(p.getTime());
                messageInfos.add(talkRecord);
            });
        }
        talkRecordRequestDTO.setCallRecordsList(messageInfos);
        userDataBackFlowDubboService.talkRecord(talkRecordRequestDTO);
        return Empty.getInstance();
    }


    @AuthIgnore
    @PostMapping("/applicationList")
    @ApiModelProperty("APP安装列表信息回流-鲁静")
    @ApiOperation("APP安装列表信息回流-鲁静（登录成功后、授信前、借款前上传授权信息）")
    public Empty applicationList(@RequestBody @Valid ApplicationListRequestVO applicationListRequestVO){
        logger.info("APP安装列表信息回流applicationList{}", JSONObject.toJSONString(applicationListRequestVO));
        String userId = PrincipalContext.getUserId();
        logger.info("APP安装列表信息回流userId = {}", userId);
        ApplicationListRequestDTO applicationListRequest = new ApplicationListRequestDTO();
        applicationListRequest.setDeviceId(applicationListRequestVO.getDeviceId());
        applicationListRequest.setUserId(userId);
        List<ApplicationListRequestVO.Application> application = applicationListRequestVO.getAppInstallList();
        List<ApplicationListRequestDTO.Application> applicationList = new ArrayList<>();
        if(!application.isEmpty()){
            application.forEach(p -> {
                ApplicationListRequestDTO.Application appli = new ApplicationListRequestDTO.Application();
                appli.setName(p.getName());
                applicationList.add(appli);
            });
        }
        applicationListRequest.setMessageList(applicationList);
        userDataBackFlowDubboService.applicationList(applicationListRequest);
        return Empty.getInstance();
    }



}
